/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista;

import dao.UsuarioDao;
import daoimp.UsuarioDaoImp;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.dominio.Usuario;

/**
 *
 * @author Gera
 */
public class ABMLUsuario extends javax.swing.JDialog {

    ArrayList<Usuario> listaUsuario = new ArrayList<Usuario>();
    UsuarioDao uDao = new UsuarioDaoImp();
    Usuario usu = new Usuario();
    /**
     * Creates new form ABMLUsuario
     */
    public ABMLUsuario(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        listaUsuario = uDao.getAll();
        this.cargarTabla();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblUsuario = new javax.swing.JTable();
        btnNuevoUsuario = new javax.swing.JButton();
        btnModificarUsuario = new javax.swing.JButton();
        btnCancelarNU = new javax.swing.JButton();
        btnEliminarUsu = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        tblUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Usuario", "Rol"
            }
        ));
        tblUsuario.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tblUsuario);

        btnNuevoUsuario.setText("Nuevo");
        btnNuevoUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoUsuarioActionPerformed(evt);
            }
        });

        btnModificarUsuario.setText("Modificar");
        btnModificarUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarUsuarioActionPerformed(evt);
            }
        });

        btnCancelarNU.setText("Salir");
        btnCancelarNU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarNUActionPerformed(evt);
            }
        });

        btnEliminarUsu.setText("Eliminar");
        btnEliminarUsu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarUsuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(btnNuevoUsuario)
                        .addGap(18, 18, 18)
                        .addComponent(btnModificarUsuario)
                        .addGap(18, 18, 18)
                        .addComponent(btnEliminarUsu)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelarNU)
                        .addGap(0, 45, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNuevoUsuario)
                    .addComponent(btnModificarUsuario)
                    .addComponent(btnEliminarUsu)
                    .addComponent(btnCancelarNU))
                .addGap(25, 25, 25))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelarNUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarNUActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarNUActionPerformed

    private void btnNuevoUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoUsuarioActionPerformed
        // TODO add your handling code here:
        AltaUsuario altaU = new AltaUsuario(null, true);
        altaU.setVisible(true);
        altaU.setLocationRelativeTo(this);
        this.limpiarTabla();
        listaUsuario = uDao.getAll();
        this.cargarTabla();
    }//GEN-LAST:event_btnNuevoUsuarioActionPerformed

    private void btnModificarUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarUsuarioActionPerformed
        // TODO add your handling code here:
        String id = (String) tblUsuario.getValueAt(tblUsuario.getSelectedRow(), 0);
        usu=uDao.getUsuario(Integer.parseInt(id));
        AltaUsuario au = new AltaUsuario(null, true, usu);
        au.setVisible(true);
        au.setLocationRelativeTo(this);
        this.limpiarTabla();
        listaUsuario=uDao.getAll();
        this.cargarTabla();
    }//GEN-LAST:event_btnModificarUsuarioActionPerformed

    private void btnEliminarUsuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarUsuActionPerformed
        // TODO add your handling code here:
        try{           
                String id = (String) tblUsuario.getValueAt(tblUsuario.getSelectedRow(), 0);
                usu=uDao.getUsuario(Integer.parseInt(id));
                int i = JOptionPane.showConfirmDialog(this,"¿Desea Eliminar?","Eliminar",JOptionPane.YES_NO_OPTION);
                if(i == 0){
                    uDao.delete(usu);
                this.limpiarTabla();
                listaUsuario=uDao.getAll();
                this.cargarTabla();
            }
        }catch(ArrayIndexOutOfBoundsException e ){
             JOptionPane.showMessageDialog(this, "Seleccione un elemento de la lista");   
        }
    }//GEN-LAST:event_btnEliminarUsuActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ABMLUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ABMLUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ABMLUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ABMLUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ABMLUsuario dialog = new ABMLUsuario(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelarNU;
    private javax.swing.JButton btnEliminarUsu;
    private javax.swing.JButton btnModificarUsuario;
    private javax.swing.JButton btnNuevoUsuario;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblUsuario;
    // End of variables declaration//GEN-END:variables
    private void cargarTabla() {
        DefaultTableModel modelo = (DefaultTableModel) tblUsuario.getModel();
            String datos[] = new String[4];
            for(Usuario u : listaUsuario){
                datos[0]= String.valueOf(u.getIdUsuario());
                datos[1]= u.getUsuario();                
                datos[2]= String.valueOf(u.getRol());
                modelo.addRow(datos);
            }
    }
      private void limpiarTabla() {
        DefaultTableModel modelo = (DefaultTableModel) tblUsuario.getModel();
                      while(this.tblUsuario.getRowCount() !=0)
                             modelo.removeRow(0);        
    }
}
